import 'dart:async';

import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:bxultimate/app/theme/app_theme.dart';
import 'package:bxultimate/app/theme/gaps.dart';
import 'package:bxultimate/data/request/base_request.dart';
import 'package:bxultimate/domain/common/MapLatLonDto.dart';
import 'package:bxultimate/shared/shared.dart';
import 'package:bxultimate/shared/util/util_location.dart';
import 'package:bxultimate/widgets/mk_page.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';
import 'package:tdesign_flutter/tdesign_flutter.dart';
import 'controller.dart';

class MapPointSelectPage extends StatefulWidget {
  const MapPointSelectPage({Key? key}) : super(key: key);

  @override
  State<MapPointSelectPage> createState() => _MapPointSelectPageState();
}

class _MapPointSelectPageState extends State<MapPointSelectPage> {
  final controller = Get.find<MapPointSelectController>();
  final state = Get.find<MapPointSelectController>().state;

  final Map<String, Marker> _initMarkerMap = <String, Marker>{};
  late LatLng mapCenter;

  MapLatLonDto mapLatLonDto = MapLatLonDto();

  @override
  void initState() {
    super.initState();



    String? devicePosition =
        UtilSp.getString(AppConstant.DEVICE_POSITION, defValue: "");
    if(devicePosition != ''){
      var arr = devicePosition!.split(",");
      print(devicePosition);
      mapCenter = LatLng(double.parse(arr[1]), double.parse(arr[0]));
      addMarker(mapCenter);
    }
    /// 动态申请定位权限
    requestPermission();
  }

  @override
  void dispose() {
    super.dispose();
  }

  late AMapController mapController;

  // 获取审图号
  void getApprovalNumber() async {
    //普通地图审图号
    String? mapContentApprovalNumber =
        await mapController?.getMapContentApprovalNumber();
    //卫星地图审图号
    String? satelliteImageApprovalNumber =
        await mapController?.getSatelliteImageApprovalNumber();
  }

  AMapApiKey _amapApiKeys = AMapApiKey(
      androidKey: '37c7d80606950366447621bbb9681459',
      iosKey: '6dd47940595825dba26017b739221982');

  AMapPrivacyStatement _amapPrivacyStatement =
      AMapPrivacyStatement(hasContains: true, hasShow: true, hasAgree: true);

  _onMapCreated(AMapController controller) {
    setState(() {
      mapController = controller;
      getApprovalNumber();
    });
  }

  void addMarker(LatLng latLng) async {
    _initMarkerMap.clear();
    _initMarkerMap['marker'] = Marker(
      position: latLng,
      icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRose),
    );
    _initMapAddress(latLng);
  }

  @override
  Widget build(BuildContext context) {
    return MkPage(
      child: Scaffold(
        backgroundColor: Colors.transparent,
        appBar: new AppBar(
          backgroundColor: Colors.transparent,
          title: new Text('位置选择'),
        ),
        body: Stack(
          children: [
            AMapWidget(
              privacyStatement: _amapPrivacyStatement,
              apiKey: _amapApiKeys,
              onMapCreated: _onMapCreated,
              initialCameraPosition:
                  CameraPosition(target: mapCenter, zoom: 14),
              markers: Set<Marker>.of(_initMarkerMap.values),
              onTap: (latLng) {
                setState(() {
                  addMarker(latLng);
                });
              },
            ),
            Positioned(
              bottom: 0,
              child: Container(
                width: Get.width,
                height: 200,
                padding: EdgeInsets.all(AppTheme.iDefaultPadding),
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(10),
                    color: Colors.white),
                child: mapLatLonDto.address == null
                    ? Center(
                        child: Text('点击地图获取位置'),
                      )
                    : Column(
                        mainAxisAlignment: MainAxisAlignment.start,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Gaps.vGap4,
                          Text(
                            mapLatLonDto.address!,
                            style: TextStyle(
                                fontSize: 18, fontWeight: FontWeight.bold),
                          ),
                          Gaps.vGap4,
                          Text('距您${mapLatLonDto.distance!}',
                              style: TextStyle(fontSize: 14)),
                          Gaps.vGap4,
                          Text('${mapLatLonDto.name!}',
                              style: TextStyle(fontSize: 14)),
                          Gaps.vGap24,
                          TDButton(
                            text: '确认选择',
                            isBlock: true,
                            theme: TDButtonTheme.primary,
                            onTap: () {
                              Get.back(result: mapLatLonDto);
                            },
                          )
                        ],
                      ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 动态申请定位权限
  void requestPermission() async {
// 申请权限
    bool hasLocationPermission =
        await UtilPermission.requestLocationPermission();
    if (hasLocationPermission) {
      print("定位权限申请通过");
    } else {
      print("定位权限申请不通过");
    }
  }

  void _initMapAddress(LatLng latLng) async {
    mapLatLonDto =
        await BaseRequest.getLatLonAddress(latLng.latitude, latLng.longitude);
    setState(() {
      mapLatLonDto = mapLatLonDto;
    });
  }
}
